<template>
  <f7-page
    name="uploadAvatar"
    color-theme="red"
    class="backgroundColor uploadAvatar_box"
  >
    <div class="navbarUploadAvatar">
      <div class="navbar_l" @click="$f7router.back()">
        <f7-button>
          <svg-icon iconClass="horn_down_white" v-if="getThemeDark" />
          <svg-icon iconClass="horn_down" v-else />
        </f7-button>
      </div>
      <div class="navbar_m">
        <div class="mText">
          <span class="titleColor">上传头像</span>
        </div>
      </div>
      <div class="navbar_r"></div>
    </div>
    <p v-show="!finishUpload" style="margin-left:0.2rem" class="spanColor">
      jpg|jpeg|png格式的文件:
      <input
        style="margin-top:12px"
        id="avatarFile"
        @change="
          (el) => {
            handleFileChange(el)
          }
        "
        type="file"
        name="file"
      />
    </p>
    <p v-show="!finishUpload" style="margin-left:0.2rem">{{ fileTip }}</p>
    <div id="avatar_preview" v-show="finishUpload">
      <img id="preview_img" style="border-radius:50%;" />
    </div>
    <div class="container" v-show="finishUpload">
      <img src="" />
    </div>

    <f7-row
      style="margin:0.2rem 0.2rem;position:absolute;bottom:0;width:calc(100vw - 0.4rem)"
    >
      <f7-col>
        <f7-button fill @click="saveToAvatar()">提交</f7-button>
      </f7-col>
    </f7-row>
  </f7-page>
</template>
<script>
import { mapGetters,mapActions } from 'vuex'
import { dataURLtoFile } from '@/utils/index.js'
import { v4 as uuidv4 } from 'uuid'
import { uploadAvatar } from '@/api/upload.js'
export default {
  computed: {
    ...mapGetters({
      getThemeDark: 'getThemeDark',
      getUserInfo: 'getUserInfo',
    }),
  },
  mounted() {},
  data() {
    return {
      fileTip: '',
      finishUpload: false,
      formData: new FormData(),
    }
  },
  methods: {
    ...mapActions({
      setUserInfo: 'setUserInfo',
    }),
    handleFileChange(e, type) {
      const input = e.target
      const files = e.target.files
      let self = this
      if (files && files[0]) {
        const file = files[0]
        if (file.size > 1024 * 1024 * 30) {
          this.fileTip = '文件大小不能超过30M!'

          input.value = ''
          return false
        } else if (
          file.type != 'image/jpeg' &&
          file.type != 'image/png' &&
          file.type != 'image/jpg'
        ) {
          this.fileTip = '仅支持jpeg、png、jpg格式的图片'
        } else {
          function readBlobAsDataURL(blob, callback) {
            var a = new FileReader()
            a.onload = function(e) {
              callback(e.target.result)
            }
            a.readAsDataURL(blob)
          }

          readBlobAsDataURL(file, function(dataUrl) {
            self.finishUpload = true
            $('.uploadAvatar_box .container >img').attr('src', dataUrl)
            $('.uploadAvatar_box .container > img').cropper({
              aspectRatio: 1 / 1,
              crop: function(data) {
                // 出来裁切后的图片数据.
                console.log(data)
                let result = $('.uploadAvatar_box .container > img').cropper(
                  'getCroppedCanvas'
                )
                $('#preview_img').attr('src', result.toDataURL('image/png'))
              },
            })
          })
        }
      }
    },
    saveToAvatar() {
      let self = this
      if (!this.finishUpload) {
        this.$f7ready((f7) => {
          var toastTop = f7.toast.create({
            text: '请上传文件',
            position: 'top',
            closeTimeout: 1500,
          })
          toastTop.open()
        })
        return;
      }

      let result = $('.uploadAvatar_box .container > img').cropper(
        'getCroppedCanvas'
      )
      // let image = new Image();
      // image.src = result.toDataURL("image/png");
      $('#preview_img').attr('src', result.toDataURL('image/png'))
      console.log(result.toDataURL('image/png'))
      console.log(
        uuidv4()
          .split('-')
          .join('')
      )
      let File = dataURLtoFile(
        result.toDataURL('image/png'),
        uuidv4()
          .split('-')
          .join('')+'.png'
      )
      console.log(File)
      //准备提交数据
      this.formData.append('userId', this.getUserInfo.userid)
      this.formData.append('headerImg', File)
      self.$f7.dialog.preloader()
      uploadAvatar(this.formData)
        .then((res) => {
          self.$f7.dialog.close()
          if (res.code === 200) {
            let tUserInfo = JSON.parse(JSON.stringify(self.getUserInfo));
            tUserInfo.headerImgUrl = res.data.headerImgUrl;
            // self.$store.dispatch('setUserInfo', tUserInfo)
            self.setUserInfo(tUserInfo)
            this.$f7ready((f7) => {
              var toastTop = f7.toast.create({
                text: '上传成功',
                position: 'top',
                closeTimeout: 1500,
              })
              toastTop.open()
              f7.views.main.router.back()
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.navbarUploadAvatar {
  display: flex;
  align-items: center;
  height: 9vh;
  .navbar_l {
    width: 12vw;
    .svg-icon {
      width: 0.4rem;
      height: 0.4rem;
    }
  }
  .navbar_m {
    flex: 1;
    width: 72vw;
    margin-left: 1vw;
    span {
      font-size: 18px;
      white-space: nowrap;
    }
    .mText {
      width: 72vw;
    }
  }
}
#avatar_preview {
  width: 50vw;
  height: 50vw;
  margin: auto;
  margin-bottom: 10px;
}
.container {
  width: 80vw;
  height: 80vw;
  margin: auto;
}
#avatar_preview img {
  width: 100%;
  height: 100%;
}
.container img {
  width: 100%;
  height: 100%;
}
</style>
